package org.kommii.encryption;

import java.io.ByteArrayOutputStream;

public class HexHandler {
	
	private static String hexString="0123456789ABCDEF"; 
	
	/**
	 * 将16进制编码串转换为普通字符串
	 * @param s
	 * @return
	 */
	public static String toStringHex(String s) {
		byte[] baKeyword = new byte[s.length() / 2];
		for (int i = 0; i < baKeyword.length; i++) {
			try {
				baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(
						i * 2, i * 2 + 2), 16));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		try {
			s = new String(baKeyword, "utf-8");// UTF-16le:Not
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return s;
	} 
	
	/**
	 * 将一个字符串转化为16进制编码串
	 * @param s
	 * @return
	 */
	public static String toHexString(String s) {
		String str = "";
		for (int i = 0; i < s.length(); i++) {
			int ch = (int) s.charAt(i);
			String s4 = Integer.toHexString(ch);
			str = str + s4;
		}
		return str;
	} 
	
	/**
	 * 将字符串(包括中文)，转换为一个16进制编码串
	 * @param str
	 * @return
	 */
	public static String encode(String str) {
		// 根据默认编码获取字节数组
		byte[] bytes = str.getBytes();
		StringBuilder sb = new StringBuilder(bytes.length * 2);
		// 将字节数组中每个字节拆解成2位16进制整数
		for (int i = 0; i < bytes.length; i++) {
			sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));
			sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0));
		}
		return sb.toString();
	} 
	
	/**
	 * 将一个16进制编码串,转换为字符串(包括中文)
	 * @param bytes
	 * @return
	 */
	public static String decode(String bytes) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream(
				bytes.length() / 2);
		// 将每2位16进制整数组装成一个字节
		for (int i = 0; i < bytes.length(); i += 2)
			baos.write((hexString.indexOf(bytes.charAt(i)) << 4 | hexString
					.indexOf(bytes.charAt(i + 1))));
		return new String(baos.toByteArray());
	} 

	
	public static void main(String[] args) {
		String str = "声带固定术gfrg454g+*&^%#$sdgd绥芬河、额大幅度/dfh是豆腐干豆腐";
		String s = "73674e506a396579304b304e496d33713341416262413d3d";
		String t = toHexString(str);
		String tt = toStringHex(t);
		System.out.println(t);
		System.out.println(tt);
		String a = encode(str);
		String b = decode(a);
		System.out.println(a);
		System.out.println(b);
	}

}
